package com.hue.gulimailcart.web;

import com.hue.common.to.UserInfoTo;
import com.hue.gulimailcart.interceptor.LoginStatusInterceptor;
import com.hue.gulimailcart.service.CartService;
import com.hue.gulimailcart.vo.Cart;
import com.hue.gulimailcart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/12 20:41
 * @Description:
 */
@Controller
@RequestMapping("/cart")
public class CartWebController {
    @Autowired
    private CartService cartService;

    /**
     * 浏览器使用一个user-key的cookie来标识用户的身份，有效期为1个月
     * 如果第一次使用购物车功能，浏览器为创建一个临时用户（user-key）
     * 浏览器以后每次访问都会带上这个user-key
     *
     * @return
     */
    @GetMapping("/cart.html")
    public String cartList(Model model) {
        UserInfoTo userInfoTo = LoginStatusInterceptor.threadLocal.get();

        Cart cart = cartService.getCart();
        System.out.println("threadLocal:" + LoginStatusInterceptor.threadLocal);

        model.addAttribute("cart", cart);
        return "cart";
    }

    /**
     * RedirectAttributes:
     * addAttribute():将参数放在url后面
     * addFlashAttribute():将参数放在session中，可以在页面取出，但是只能取一次
     *
     * @param skuId
     * @param count
     * @param redirectAttributes
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId,
                            @RequestParam("count") Integer count,
                            RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        cartService.addToCart(skuId, count);
        redirectAttributes.addAttribute("skuId", skuId);

        return "redirect:http://cart.gulimail.com/cart/addToCart.html";
    }

    @GetMapping("/addToCart.html")
    public String addToCartHtml(@RequestParam("skuId") Long skuId, Model model) {
        CartItem cartItem = cartService.getCartItemBySkuId(skuId);
        model.addAttribute("item", cartItem);
        return "index";
    }

    @GetMapping("/checkedItem")
    public String checkedItem(@RequestParam("skuId")Long skuId,@RequestParam("check")Integer check){
        cartService.checkedItem(skuId,check);
        return "redirect:http://cart.gulimail.com/cart/cart.html";
    }
}
